package com.neusoft.nep.common;

import com.neusoft.nep.supervise.entity.FeedbackData;
import com.neusoft.nep.supervise.entity.User;
import com.neusoft.nep.supervise.entity.Grid;
import com.neusoft.nep.supervise.entity.Submission;

import com.neusoft.nep.common.FileUtils;

import java.util.HashMap;
import java.util.Map;

public class DataIntegrationUtils {

    public static void integrateData() {
        // 读取所有数据
        Map<String, User> userMap = FileUtils.readMapObject("user.txt");
        Map<String, Grid> gridMap = FileUtils.readMapObject("grid.txt");
        Map<String, Submission> submissionMap = FileUtils.readMapObject("submission.txt");

        // 读取现有的feedback数据（如果存在）
        Map<String, FeedbackData> feedbackMap = FileUtils.readMapObject("feedback1.txt");
        int successCount = 0;
        int errorCount = 0;

        // 遍历所有Submission，构建完整的反馈数据

        for (Map.Entry<String, User> userEntry : userMap.entrySet()) {
            User user = userEntry.getValue();
            String submissionId = user.getSubmissionId();

            // 检查用户是否有提交记录
            if (submissionId == null || submissionId.isEmpty()) {
                System.out.println("用户 " + user.getUserName() + " 没有提交记录，跳过");
                continue;
            }

            // 查找对应的提交记录
            Submission submission = submissionMap.get(submissionId);
            if (submission == null) {
                System.out.println("找不到提交记录 ID: " + submissionId + "，跳过用户: " + user.getUserName());
                errorCount++;
                continue;
            }

            // 查找对应的网格记录
            String gridId = submission.getGridId();
            if (gridId == null || gridId.isEmpty()) {
                System.out.println("提交记录 " + submissionId + " 没有关联的网格ID，跳过");
                errorCount++;
                continue;
            }

            Grid grid = gridMap.get(gridId);
            if (grid == null) {
                System.out.println("找不到网格记录 ID: " + gridId + "，跳过");
                errorCount++;
                continue;
            }

            // 创建完整的整合数据
            FeedbackData feedbackData = new FeedbackData(
                    submission.getId(),
                    user.getUserName(),
                    user.getGender(),
                    user.getBirthday(),
                    user.getPhoneNumber(),
                    grid.getProvince(),
                    grid.getCity(),
                    submission.getFeedback(),
                    submission.getAQI(),
                    submission.getDate()
            );

            // 保存整合后的数据
            feedbackMap.put(submissionId, feedbackData);
            successCount++;
        }

        // 写入整合后的数据
        FileUtils.writeMapObject("feedback1.txt", feedbackMap);
        Dialog.showDialog("反馈提交", "反馈成功提交");
    }
}